package com.zwj.config.aspect;

import com.zwj.vo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;

/**
 * 处理方法的请求参数与响应参数
 *
 * @author 摸鱼二长老
 * @version 1.0
 * @createTime 2023/10/22 20:09
 */
@Slf4j
@Aspect
@Component
public class EsbAspect {

    @Pointcut(value = "@annotation(com.zwj.config.annotaion.Esb)")
    public void pointCut() {

    }

    /**
     * 处理请求与响应数据
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("pointCut()")
    public Object handleResultAndResponse(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取参数
        Object[] args = joinPoint.getArgs();
        //非空判断
        if (args.length == 0 || args == null) {
            return joinPoint.proceed();
        }
        for (Object param : args) {
            beforeProcess(param);
        }

        Object result = joinPoint.proceed();
        afterProcess(result);
        return result;
    }

    /**
     * 前置处理
     * 将"null"或者”“替换成null
     *
     * @param obj 需要处理的类
     * @throws IllegalAccessException
     */
    public void beforeProcess(Object obj) throws IllegalAccessException {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            Object fieldValue = field.get(obj);

            // 处理当前成员变量
            if (field.getType().equals(String.class)) {
                log.error("字段:{},是String类型", field.getName());
                //业务处理
                if ("null".equals(fieldValue) || "".equals(fieldValue)) {
                    log.error("     字段:{},value:{}", field.getName(), fieldValue);
                    field.set(obj, null);
                }
            }
            if (field.getType().getName().startsWith("com.zwj.vo")){
                beforeProcess(fieldValue);
            }
        }
    }

    /**
     * 后置处理：将null转为“”
     *
     * @param obj 需要处理的类
     * @throws IllegalAccessException
     */
    public void afterProcess(Object obj) throws IllegalAccessException {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            Object fieldValue = field.get(obj);

            // 处理当前成员变量
            if (field.getType().equals(String.class)) {
                if (ObjectUtils.isEmpty(fieldValue)) {
                    field.set(obj, "");
                }
            }

            // 如果当前成员变量是对象类型，则递归处理
            if (field.getType().getName().startsWith("com.zwj.vo")){
                afterProcess(fieldValue);
            }
        }
    }
}
